package org.durandj.ystream.client.ui;

import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.JButton;

import javax.swing.JEditorPane;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.event.HyperlinkEvent.EventType;

/**
 * A dialog for setting/changing VLC related settings.
 */
public class VLCDialog extends javax.swing.JDialog
{
	{
		//Set Look & Feel
		try {
			javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	private static final long serialVersionUID = 8045857877770229918L;
	
	/**
	 * The user hit OK and the data was verified successfully!
	 */
	public static final int RESULT_OK = 0;
	
	/**
	 * The user hit cancel.
	 */
	public static final int RESULT_CANCEL = 1;
	
	private JEditorPane txtInformation;
	private JPanel panel;
	private JButton btnOk;
	private JButton btnBrowse;
	private JTextField txtPath;
	
	/**
	 * The result of the window closing.
	 */
	private int result;
	
	/**
	 * The currently selected for VLC.
	 */
	private String directory;

	public VLCDialog(JFrame frame)
	{
		super(frame);
		initGUI();
		
		result = -1;
		directory = null;
	}
	
	private void initGUI()
	{
		try
		{
			{
				BorderLayout thisLayout = new BorderLayout();
				getContentPane().setLayout(thisLayout);
				this.setTitle("Get VLC");
				this.setName("Get VLC");
				this.setResizable(false);
				this.setModal(true);
				{
					txtInformation = new JEditorPane();
					txtInformation.setContentType("text/html");
					getContentPane().add(txtInformation, BorderLayout.CENTER);
					txtInformation.setEditable(false);
					// Info text fixed by nickiannone
					txtInformation.setText("YStream uses your system's VLC installation to handle music playing. To be able to use" +
					                       "VLC, however, you need to tell YStream where you installed it. You can copy the link directly" +
					                       "into the text box below or you can browse to the folder by hitting the Browse button. If" +
					                       "you do not have VLC installed, you can get it for free by clicking " +
					                       "<a href=\"http://www.videolan.org/vlc/\">here.</a><br>");
					txtInformation.addHyperlinkListener(new HyperlinkListener() {
						@Override
						public void hyperlinkUpdate(HyperlinkEvent e)
						{
							if(e.getEventType() == EventType.ACTIVATED)
							{
								// Lets get that browser open!
								Desktop desktop = Desktop.getDesktop();
								try
								{
									desktop.browse(new URI("http://www.videolan.org/vlc/"));
								}
								catch(IOException ioe)
								{
									// TODO Auto-generated catch block
									ioe.printStackTrace();
								}
								catch(URISyntaxException urie)
								{
									// TODO Auto-generated catch block
									urie.printStackTrace();
								}
							}
							else if(e.getEventType() == EventType.ENTERED)
								txtInformation.setToolTipText("Opens your default browser to the VideoLAN page.");
							else
								txtInformation.setToolTipText(null);
						}
					});
				}
				{
					panel = new JPanel();
					getContentPane().add(panel, BorderLayout.SOUTH);
					panel.setPreferredSize(new java.awt.Dimension(600, 72));
					panel.setLayout(null);
					{
						txtPath = new JTextField();
						panel.add(txtPath);
						txtPath.setBounds(6, 6, 506, 23);
					}
					{
						btnBrowse = new JButton();
						panel.add(btnBrowse);
						btnBrowse.setText("Browse");
						btnBrowse.setBounds(518, 4, 70, 28);
						
						btnBrowse.addActionListener(new ActionListener() {
							@Override
							public void actionPerformed(ActionEvent arg0)
							{
								JFileChooser fc = new JFileChooser();
								fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
								fc.setMultiSelectionEnabled(false);
								int result = fc.showOpenDialog(getParent());
								
								if(result == JFileChooser.CANCEL_OPTION)
									return;
								
								txtPath.setText(fc.getSelectedFile().getAbsolutePath());
							}
						});
					}
					{
						btnOk = new JButton();
						panel.add(btnOk);
						btnOk.setText("OK");
						btnOk.setBounds(543, 38, 45, 28);
						
						btnOk.addActionListener(new ActionListener() {
							@Override
							public void actionPerformed(ActionEvent e)
							{
								// Lets verify the directory they gave...
								String path = txtPath.getText();
								
								// TODO Clarify error messages?
								if(path.isEmpty())
								{
									JOptionPane.showMessageDialog(getParent(),
									                              "You must specify the directory of VLC to use YStream.",
									                              "VLC Directory Issue",
									                              JOptionPane.ERROR_MESSAGE);
									return;
								}
								
								File d = new File(path);
								if(!d.exists())
								{
									JOptionPane.showMessageDialog(getParent(),
									                              "You must specify a valid directory that contains VLC to use YStream.",
									                              "VLC Directory Issue",
									                              JOptionPane.ERROR_MESSAGE);
									return;
								}
								else if(!d.isDirectory())
								{
									JOptionPane.showMessageDialog(getParent(),
									                              "You must specify a directory containing VLC to use YStream.",
									                              "VLC Directory Issue",
									                              JOptionPane.ERROR_MESSAGE);
									return;
								}
								
								// Well they've supplied a directory so now lets make sure it has VLC stuff in it.
								boolean check = false;
								File files[] = d.listFiles();
								for(File f : files)
								{
									if(f.getName().equals("libvlc.dll"))
									{
										check = true;
										break;
									}
								}
								
								if(!check)
								{
									JOptionPane.showMessageDialog(getParent(),
									                              "You musct specify the directory that contains VLC to use YStream.",
									                              "VLC Directory Issue",
									                              JOptionPane.ERROR_MESSAGE);
									return;
								}
								
								// The given path has passed all the tests so lets report it!
								directory = path;
								result = RESULT_OK;
								setVisible(false);
							}
						});
					}
				}
			}
			this.setSize(600, 170);
			this.setLocationRelativeTo(this.getParent());
			
			// We need to know some specifics about what happens to the window so lets listen in.
			addWindowListener(new WindowAdapter() {
				@Override
				public void windowClosing(WindowEvent e)
				{
					if(result != RESULT_OK)
						result = RESULT_CANCEL;
				}
			});
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * Gets the result of the window. This could be <code>RESULT_OK</code> for success, <code>RESULT_CANCEL</code> for failure, or -1 if
	 * the dialog has not closed yet.
	 * 
	 * @return the result of the dialog
	 */
	public int getResult()
	{
		return result;
	}
	
	/**
	 * Returns the selected directory of VLC.
	 * 
	 * @return the path to VLC
	 */
	public String getPath()
	{
		return directory;
	}
	
	/**
	 * The current VLC directory.
	 * 
	 * @param directory - the directory
	 */
	public void setPath(String directory)
	{
		if(directory == null)
			throw new NullPointerException("Must define file path.");
		
		this.directory = directory;
		txtPath.setText(this.directory);
	}
}
